<template>
  <div class="">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div>
          <el-form-item>
            <el-input v-model="key" clearable placeholder="请输入查询内容" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="分类：">
            <el-cascader v-model="tid" :props="{ checkStrictly: true,value:'id',label:'tname',emitPath:false,expandTrigger: 'hover' }" :options="tidList" clearable />
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="state" placeholder="状态">
              <el-option key="0" label="全部" value="0" />
              <el-option key="1" label="上架" value="1" />
              <el-option key="2" label="下架" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getData">查询</el-button>
          </el-form-item>
        </div>
        <div>
          <el-form-item>
            <el-button type="primary" @click="onVisible(1)">新增商品</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
      <!-- 展开项 -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form v-if="props.row.couponDetail.gid" label-position="left" inline class="demo-table-expand" style="padding-left:20px">
            <el-form-item label="发行总量:">
              <span>{{ props.row.couponDetail.tcount }}</span>
              <el-button v-if="props.row.couponDetail.id" type="primary" style="margin-left:20px" @click="couponShow = true;couponType=2;couponObj.gid=props.row.couponDetail.gid">增量</el-button>
            </el-form-item>
            <el-form-item label="单张券包含商品数:">
              <span>{{ props.row.couponDetail.gcount }}</span>
            </el-form-item>
            <el-form-item label="待发行数量:">
              <span>{{ props.row.couponDetail.rcount }}</span>
              <el-button v-if="props.row.couponDetail.rstate!=2&&props.row.couponDetail.rcount>0" type="primary" style="margin-left:20px" @click="ReleaseFn(props.row.couponDetail.gid)">发布</el-button>
            </el-form-item>
            <el-form-item label="发行状态:">
              <span>{{ props.row.couponDetail.rstate==3?'已发行':props.row.couponDetail.rstate==2?'待发行':'未发行' }}</span>
            </el-form-item>
            <el-form-item label="过期时间:">
              <span>{{ props.row.couponDetail.otime.replace("T"," ") }}</span>
            </el-form-item>
          </el-form>
          <div class="btnFn" style="padding-left:20px">
            <el-button v-if="!props.row.couponDetail.gid" type="primary" @click="couponShow = true;couponType=1;couponObj.gid=props.row.id">添加兑换券</el-button>
            <el-button v-if="props.row.couponDetail.gid" type="primary" @click="$router.push({name:'CouponList',query:{gid:props.row.couponDetail.gid}})">领取详情</el-button>
          </div>
        </template>
      </el-table-column>
      <!-- 商品列信息 -->
      <el-table-column prop="id" label="ID" width="100" align="center" />
      <el-table-column prop="bannerpicurl" label="商品封面" width="80" align="center">
        <template slot-scope="scope">
          <el-avatar shape="square" :size="50" :src="scope.row.bannerpicurl.split(',')[0]" />
        </template>
      </el-table-column>
      <el-table-column prop="goodsname" show-overflow-tooltip width="300" label="商品名称" align="center" />
      <el-table-column label="所属分类" align="center">
        <template slot-scope="scope">
          <el-cascader v-model="scope.row.tidArr" width="400px" :props="{value:'id',label:'tname'}" disabled :options="tidList" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="单价" align="center" />
      <el-table-column prop="stock" label="库存" align="center" />
      <el-table-column prop="state" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="0" @change="(val)=>{ return SetValid(val,scope.row.id)}" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="onVisible(2, scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-if="totalCount>10" layout="prev, pager, next" :total="totalCount" @current-change="idx=>{PageIndex = idx}" />
    <!-- 新增商品 -->
    <el-dialog width="800px" :close-on-click-modal="false" title="新增商品" :visible.sync="dialogVisible" @open="openDialog" @closed="handleClose">
      <el-form id="forms" ref="forms" :rules="rulesModel" :model="form" label-width="100px" style="max-height: 600px;overflow-y: scroll;">
        <div>
          <el-form-item label="商品图片">
            <el-upload ref="upload" :action="uploadUrl" :file-list="picurlsArr" :headers="headers" list-type="picture-card" :on-success="quillImgSuccess" :on-preview="handleSuccess" :on-remove="handleRemove">
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item label="商品名称" prop="goodsname">
          <el-input v-model="form.goodsname" type="textarea" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="置顶推荐">
          <el-checkbox v-model="form.istop" :true-label="1">置顶推荐</el-checkbox>
        </el-form-item>
        <div style="display: flex;">
          <!-- 选择分类 -->
          <el-form-item label="选择分类">
            <el-cascader v-model="tidArr" width="400px" placeholder="选择分类" :props="cascaderProps" :options="tidList" clearable />
          </el-form-item>
        </div>
        <div style="display: flex;">
          <el-form-item label="单价" prop="price">
            <el-input v-model="form.price" placeholder="请输入商品单价" />
          </el-form-item>
        </div>
        <div style="display: flex;">
          <el-form-item label="库存" prop="stock">
            <el-input v-model.number="form.stock" :rows="2" placeholder="请输入商品库存" />
          </el-form-item>
        </div>
        <el-form-item label="上架/下架" prop="state">
          <el-switch v-model="form.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <div>
          <editor v-model="form.content" />
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="onEdit(1)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogImg">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!-- 新增兑换券 新增数量   修改发行 -->
    <el-dialog :close-on-click-modal="false" :title="couponType==1?'新增兑换券':couponType==2?'新增数量':''" :visible.sync="couponShow">
      <el-form label-width="100px">
        <el-form-item v-if="couponType==1" label="标题">
          <el-input v-model="couponObj.title" placeholder="标题" />
        </el-form-item>
        <el-form-item v-if="couponType==1||couponType==2" label="兑换券数量">
          <el-input v-model="couponObj.count" :placeholder="couponType==1?'请输入发行数量':'请输入新增数量'" />
        </el-form-item>
        <el-form-item v-if="couponType==1" label="可兑换商品">
          <el-input v-model="couponObj.gcount" placeholder="请输入单张兑换券可兑换商品数量" />
        </el-form-item>
        <el-form-item v-if="couponType==1" label="过期时间">
          <el-date-picker v-model="couponObj.otime" type="date" placeholder="选择日期" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="couponShow = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="confirmFn()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import editor from '../../../components/Editor/index.vue'
import {
  getgoodstypepage,
  getgoodspage,
  GoodsEdti,
  DeleteShopgoods,
  GoodsFirst,
  SetState
} from '@/api/goods.js'
import {
  first,
  releaseAdd,
  Release,
  releaseAddCount,
  releaseEdit,
  CouponPage,
  Coupon_excel
} from '@/api/coupon.js'
import ipConfig from '../../../../ip-config'
export default {
  name: 'Name',
  components: { editor },
  data() {
    return {
      dialogImageUrl: '',
      dialogImg: false,
      dialogVideo: false,
      dialogVideoUrl: '',
      uploadUrl:
      ipConfig.baseIP + "/ctrls/Upload?type='img'&file_type=''",
      headers: {
        TOKEN: getToken()
      },
      loading: false,
      key: '',
      state: '',
      tid: '',
      istop: '',
      tidList: [],
      listLoading: false,
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      dialogVisible: false,
      visibleType: '',
      form: {},
      rulesModel: {
        goodsname: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入商品单价', trigger: 'blur' }],
        bannerpicurl: [
          { required: true, message: '请上传商品图片', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入商品描述', trigger: 'blur' }
        ],
        state: [{ required: true, message: '请选择商品状态', trigger: 'blur' }],
        stock: [{ required: true, message: '请设置商品库存', trigger: 'blur' }]
      },
      tidArr: [], // 分类
      picurlsArr: [], // 图片
      cascaderProps: {
        value: 'id',
        label: 'tname'
      },
      // 兑换券 新增
      couponShow: false,
      detailLoading: false,
      couponObj: {
        gid: '', // 商品ID
        count: '', // 发行数量
        gcount: '', // 商品发货数量
        title: '', // 标题
        otime: '' // 过期时间
      },
      couponType: 1 //  1  新增发行   2  新增数量  3  修改发行
    }
  },
  computed: {},
  watch: {
    PageIndex(val) {
      console.log(val)
      this.getData()
    }
  },
  mounted() {
    this.getData()
    setTimeout(() => {
      this.getPid()
    }, 500)
  },
  methods: {
    inintCouponData() {
      this.couponObj.gid = ''
      this.couponObj.count = ''
      this.couponObj.gcount = ''
      this.couponObj.title = ''
      this.couponObj.otime = ''
    },
    // 兑换券 启用禁用
    async SetStateFn() {
      await SetState({
        gid: gid,
        state: state
      })
    },
    // 兑换券 修改发行
    async releaseEditFn() {
      await releaseEdit({
        gid: gid,
        title: title,
        otime
      })
    },
    // 兑换券 增加发行数量
    async releaseAddCountFn() {
      const { success, msg } = await releaseAddCount({
        gid: this.couponObj.gid,
        count: this.couponObj.count
      })
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
      if (success) {
        this.couponShow = false
        this.getData()
        this.inintCouponData()
      }
    },
    // 兑换券 执行发行
    async ReleaseFn(id) {
      const { success, msg } = await Release({
        gid: id
      })
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
      if (success) {
        this.getData()
      }
    },
    // 兑换券 新增发行
    async releaseAddFn() {
      if (
        this.couponObj.count == '' ||
        this.couponObj.gcount == '' ||
        this.couponObj.title == '' ||
        this.couponObj.otime == ''
      ) {
        this.$message({
          message: '请完善资料',
          type: 'error'
        })
        return
      }
      const { success, msg } = await releaseAdd(this.couponObj)
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
      if (success) {
        this.couponShow = false
        this.getData()
        this.inintCouponData()
      }
    },

    async confirmFn() {
      // 兑换券 新增发行
      if (this.couponType == 1) {
        this.releaseAddFn()
      }
      // 兑换券 增加发行数量
      if (this.couponType == 2) {
        this.releaseAddCountFn()
      }
    },
    async getFisrt() {},
    setForm() {
      this.form = {
        id: 0,
        goodsname: '', // 商品名称
        price: '',
        costprice: '0', // 成本价
        marketprice: '0', // 市场价
        state: 1,
        stock: '',
        istop: '',
        content: '',
        bannerpicurl: '',
        tid1: '', // 一级分类
        tid2: '' // 二级分类
      }
    },
    // 上传成功
    quillImgSuccess({ success, data }) {
      if (success) {
        this.picurlsArr.push({
          name: '',
          url: data
        })
        console.log(this.picurlsArr)
      } else {
        this.$message.error('图片插入失败')
      }
    },
    // 删除
    handleRemove({ url }) {
      console.log('url===>', url)
      const a = this.picurlsArr.filter(item => {
        return item.url !== url
      })
      this.picurlsArr = a
    },
    // 预览
    handleSuccess(file) {
      this.dialogImageUrl = file.url
      this.dialogImg = true
    },
    // 分组筛选
    group(arr, parentId, isChild = 1) {
      const tree = []
      arr.map(item => {
        if (isChild === 1) {
          if (item.pid === parentId) {
            if (this.group(arr, item.id, isChild + 1).length > 0) {
              item.children = this.group(arr, item.id, isChild + 1)
            }
            tree.push(item)
          }
        }
        if (isChild === 2) {
          if (item.pid === parentId) {
            if (this.group(arr, item.id, isChild + 1).length > 0) {
              item.children = this.group(arr, item.id, isChild + 1)
            }
            tree.push(item)
          }
        }
      })
      return tree
    },
    // 获取分类
    async getPid() {
      const { list } = await getgoodstypepage({
        PageIndex: '1',
        PageSize: '10000'
      })
      this.tidList = this.group(list, 0)
    },
    async onDelete(item) {
      try {
        const confirm = await this.$confirm(
          '此操作将删除该配置, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        if (confirm === 'confirm') {
          const { success, msg } = await DeleteShopgoods([item.id])
          this.getData()
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
        }
      } catch (e) {
        // 取消
        console.log(e)
      }
    },
    // 状态
    async SetValid(val, id) {
      const { success, msg } = await SetState({
        gid: id,
        state: val
      })
      if (success) {
        this.getData()
      }
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
    },
    // 编辑
    onEdit() {
      this.$refs['forms'].validate(async valid => {
        if (valid) {
          // 图片序列化
          const imgarr = []
          this.picurlsArr.forEach(item => {
            imgarr.push(item.url)
          })
          this.form.bannerpicurl = imgarr.toString()
          this.form.tid2 = Number(this.tidArr[1]) || 0
          this.form.tid1 = Number(this.tidArr[0]) || 0
          this.form.istop = Number(this.form.istop) || 0
          this.form.price = Number(this.form.price) || 0
          this.form.marketprice = Number(this.form.marketprice) || 0
          this.form.costprice = Number(this.form.costprice) || 0
          this.form.stock = Number(this.form.stock) || 0
          this.loading = true
          const { success, msg } = await GoodsEdti(this.form)
          this.loading = false
          if (success) {
            this.dialogVisible = false
            this.getData()
          }
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
        } else {
          this.loading = false
          return false
        }
      })
    },
    // 关闭前
    handleClose() {
      this.setForm()
      this.$refs.forms.resetFields()
      this.$refs.forms.clearValidate()
      this.$refs.upload.clearFiles()
      console.log(this.form)
    },
    openDialog() {
      this.$nextTick(() => {
        document.getElementById('forms').scrollTop = 0
      })
    },
    // 打开前
    async onVisible(type, item = {}) {
      this.visibleType = type
      this.setForm()
      if (type === 2) {
        this.picurlsArr = []
        const { data } = await GoodsFirst({
          id: item.id
        })
        this.form = { ...data }
        this.tidArr = []
        const a = this.form.bannerpicurl.split(',')
        a.forEach(item => {
          this.picurlsArr.push({
            url: item
          })
        })
        this.tidArr = [this.form.tid1 || 1, this.form.tid2]
      }
      this.dialogVisible = true
    },
    async onSearch() {},
    async getData() {
      this.listLoading = true
      const { list, totalCount } = await getgoodspage({
        key: this.key,
        tid: this.tid,
        state: this.state,
        PageIndex: this.PageIndex,
        PageSize: this.pageSize
      })
      for (const item of list) {
        item.tidArr = [item.tid1, item.tid2]
        item.couponDetail = await first({
          gid: item.id
        })
      }
      this.totalCount = totalCount
      this.tableData = list
      this.listLoading = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
  padding: 4px 0px;
}
</style>
